package com.hrc.rpc.netty.handler.service;


import com.hrc.rpc.Filter.FilterConfig;
import com.hrc.rpc.Filter.FilterData;
import com.hrc.rpc.Filter.client.ClientLogFilter;
import com.hrc.rpc.common.constants.MsgStatus;
import com.hrc.rpc.protocol.MsgHeader;
import com.hrc.rpc.protocol.RpcProtocol;
import com.hrc.rpc.protocol.RpcRequest;
import com.hrc.rpc.protocol.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Slf4j
public class ServiceBeforeFilterHandler extends SimpleChannelInboundHandler<RpcProtocol<RpcRequest>> {

    private final Logger logger = LoggerFactory.getLogger(ClientLogFilter.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcProtocol<RpcRequest> protocol) {
        final RpcRequest request = protocol.getBody();
        final FilterData filterData = new FilterData(request);
        RpcResponse response = new RpcResponse();
        MsgHeader header = protocol.getHeader();
        try {
            FilterConfig.getServiceBeforeFilterChain().doFilter(filterData);
        } catch (Exception exception) {
            RpcProtocol<RpcResponse> resProtocol = new RpcProtocol<>();
            header.setStatus((byte) MsgStatus.FAILED.ordinal());
            response.setException(exception);
            logger.error("before process request {} error", header.getRequestId(), exception);
            resProtocol.setHeader(header);
            resProtocol.setBody(response);
            ctx.writeAndFlush(resProtocol);
            return;
        }
        ctx.fireChannelRead(protocol);
    }
}
